package com.dev.security.interceptor;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.http.HttpUtil;
import com.dev.security.entity.Log;
import com.dev.security.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器
 *
 * @author yuboon
 * @version v1.0
 * @date 2020/04/11
 */
public class LogInterceptor implements HandlerInterceptor {

    @Autowired
    private LogService logService;

    /**
     * 方法执行前，  如果返回false，请求就回返回，其余拦截器将不执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long start = System.currentTimeMillis();
        request.setAttribute("startTime", start);
        return true;
    }

    /**
     * 方法执行后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 渲染完成后执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long start = (Long)request.getAttribute("startTime");
        long end = System.currentTimeMillis();

        long cost = end - start;
        Log log = new Log();
        log.setUserId(10);
        log.setUserName("超级用户");
        log.setCost(cost);
        log.setIpAddress(HttpUtil.getClientIP(request));
        log.setRequestPath(request.getRequestURI());
        log.setIsError(0);

        if(ex != null){
            log.setIsError(1);
            log.setError(ExceptionUtil.stacktraceToString(ex));
        }

        logService.save(log);

    }
}
